package com.winning.pmph.utils;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hslf.usermodel.HSLFShape;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
import org.apache.poi.hslf.usermodel.HSLFTextRun;
import org.apache.poi.hslf.usermodel.HSLFTextShape;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

public class PptToImg {
	public static void main(String[] args) {
		String path = "D:/aa/1.第六章 原文.pdf";
		// convertPptToImg(path);
		//pptx2Png(path);
		pdfToImg(path);
	}
	
	public static void pdfToImg(String pdfPath) {
        if(StringUtils.isBlank(pdfPath)) {
            return;
        }
        Document document = new Document();
        try {
            document.setFile(pdfPath);
            String savePath = pdfPath.substring(0,pdfPath.lastIndexOf("."));
            File fileDir = new File(savePath);
            if(!fileDir.exists()) {
            	fileDir.mkdirs();
            }
            int pages = document.getNumberOfPages();
            for (int i = 0; i < pages; i++) {
            	RenderedImage rendImage = (BufferedImage)document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, 0, 2.5f);
            	String temp = savePath+"/"+(i+1)+".png";
                File file = new File(temp);
                ImageIO.write(rendImage, "png", file);
			}
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            document.dispose();
        }
	}

	public static void convertPptToImg(String pptPath) {
		if (StringUtils.isBlank(pptPath)) {
			return;
		}
		String suffix = pptPath.substring(pptPath.lastIndexOf(".")).toLowerCase();
		if (".pptx".equals(suffix)) {
			pptx2Png(pptPath);
		} else {
			ppt2Png(pptPath);
		}
	}

	public static boolean pptxToImg(String pptPath) {
		File file = new File(pptPath);
		String pptImgPath = pptPath.substring(0, pptPath.lastIndexOf("."));
		File outPathFile = new File(pptImgPath);
		if (!outPathFile.exists()) {
			outPathFile.mkdirs();
		}
		FileInputStream is = null;
		try {
			is = new FileInputStream(file);
			XMLSlideShow xmlSlideShow = new XMLSlideShow(is);
			is.close();
			// 获取大小
			Dimension pgsize = xmlSlideShow.getPageSize();
			// 获取幻灯片
			List<XSLFSlide> slides = xmlSlideShow.getSlides();
			for (int i = 0; i < slides.size(); i++) {
				// 解决乱码问题
				List<XSLFShape> shapes = slides.get(i).getShapes();
				for (XSLFShape shape : shapes) {
					if (shape instanceof XSLFTextShape) {
						XSLFTextShape sh = (XSLFTextShape) shape;
						List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
						for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
							List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
							for (XSLFTextRun xslfTextRun : textRuns) {
								xslfTextRun.setFontFamily("宋体");
							}
						}
					}
				}
				// 根据幻灯片大小生成图片
				BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
				Graphics2D graphics = img.createGraphics();
				graphics.setPaint(Color.white);
				graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
				// 最核心的代码
				slides.get(i).draw(graphics);
				// 图片将要存放的路径
				String absolutePath = pptImgPath + "/" + (i + 1) + ".png";
				File jpegFile = new File(absolutePath);
				// 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
				FileOutputStream out = new FileOutputStream(jpegFile);
				// 写入到图片中去
				ImageIO.write(img, "png", out);
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean pptToImg(String pptPath) {
		File file = new File(pptPath);
		String outImgPath = pptPath.substring(0, pptPath.lastIndexOf("."));
		File outPathFile = new File(outImgPath);
		if (!outPathFile.exists()) {
			outPathFile.mkdirs();
		}
		try {

			FileInputStream is = new FileInputStream(file);
			HSLFSlideShow ppt = new HSLFSlideShow(is);
			is.close();

			Dimension pgsize = ppt.getPageSize();
			List<HSLFSlide> listSlide = ppt.getSlides();
			int idx = 1;
			for (HSLFSlide slide : listSlide) {

				for (HSLFShape shape : slide.getShapes()) {
					if (shape instanceof HSLFTextShape) {
						HSLFTextShape hslfTextShape = (HSLFTextShape) shape;
						for (HSLFTextParagraph hslfTextParagraph : hslfTextShape) {
							for (HSLFTextRun hslfTextRun : hslfTextParagraph) {
								hslfTextRun.setFontFamily("宋体");
							}
						}
					}
				}

				BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
				Graphics2D graphics = img.createGraphics();
				// clear the drawing area
				graphics.setPaint(Color.white);
				graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

				// render
				slide.draw(graphics);

				// save the output
				String outPath = outImgPath + "/" + idx + ".png";
				File jpegFile = new File(outPath);
				FileOutputStream out = new FileOutputStream(jpegFile);
				ImageIO.write(img, "png", out);
				out.close();
				idx++;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static void pptx2Png(String pptxFilePath) {
		File pptxFile = new File(pptxFilePath);
		String outImgPath = pptxFilePath.substring(0, pptxFilePath.lastIndexOf("."));
		File outPathFile = new File(outImgPath);
		if (!outPathFile.exists()) {
			outPathFile.mkdirs();
		}
		FileInputStream is = null;
		// 将ppt文件转换成每一帧的图片
		XMLSlideShow pptx = null;

		try {
			ZipSecureFile.setMinInflateRatio(-1.0d);
			is = new FileInputStream(pptxFile);
			pptx = new XMLSlideShow(is);
			int idx = 1;

			Dimension pageSize = pptx.getPageSize();
			double image_rate = 1.0;
			int imageWidth = (int) Math.floor(image_rate * pageSize.getWidth());
			int imageHeight = (int) Math.floor(image_rate * pageSize.getHeight());

			for (XSLFSlide xslfSlide : pptx.getSlides()) {
				BufferedImage img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
				Graphics2D graphics = img.createGraphics();
				graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
				graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
				graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
						RenderingHints.VALUE_FRACTIONALMETRICS_ON);
				// clear the drawing area
				graphics.setPaint(Color.white);
				graphics.fill(new Rectangle2D.Float(0, 0, imageWidth, imageHeight));
				graphics.scale(image_rate, image_rate);

				// 防止中文乱码
				for (XSLFShape shape : xslfSlide.getShapes()) {
					if (shape instanceof XSLFTextShape) {
						XSLFTextShape xslfTextShape = (XSLFTextShape) shape;
						for (XSLFTextParagraph xslfTextParagraph : xslfTextShape) {
							for (XSLFTextRun xslfTextRun : xslfTextParagraph) {
								xslfTextRun.setFontFamily("宋体");
							}
						}
					}
				}

				FileOutputStream out = null;
				try {
					xslfSlide.draw(graphics);
					File pngFile = new File(outImgPath+"/"+idx+".png");
					out = new FileOutputStream(pngFile);
					ImageIO.write(img, "png", out);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (out != null) {
							out.flush();
							out.close();
						}

						if (graphics != null) {
							graphics.dispose();
						}

						if (img != null) {
							img.flush();
						}
					} catch (IOException e) {
					}
				}
				idx++;
			}
		} catch (Exception e) {
		} finally {
			try {
				if (is != null) {
					is.close();
				}

				if (pptx != null) {
					pptx.close();
				}
			} catch (Exception e) {
			}
		}
	}
	
	public static void ppt2Png(String pptFilePath) {
		File pptFile = new File(pptFilePath);
		String outImgPath = pptFilePath.substring(0, pptFilePath.lastIndexOf("."));
		File outPathFile = new File(outImgPath);
		if (!outPathFile.exists()) {
			outPathFile.mkdirs();
		}
        List<File> pngFileList = new ArrayList<>();
 
        FileInputStream is = null;
        // 将ppt文件转换成每一帧的图片
        HSLFSlideShow ppt = null;
 
        try {
            ZipSecureFile.setMinInflateRatio(-1.0d);
            is = new FileInputStream(pptFile);
            ppt = new HSLFSlideShow(is);
            int idx = 1;
 
            Dimension pageSize = ppt.getPageSize();
            double image_rate = 1.0;
            int imageWidth = (int) Math.floor(image_rate * pageSize.getWidth());
            int imageHeight = (int) Math.floor(image_rate * pageSize.getHeight());
 
            for (HSLFSlide slide : ppt.getSlides()) {
                BufferedImage img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, imageWidth, imageHeight));
                graphics.scale(image_rate, image_rate);
 
                //防止中文乱码
                for (HSLFShape shape : slide.getShapes()) {
                    if (shape instanceof HSLFTextShape) {
                        HSLFTextShape hslfTextShape = (HSLFTextShape) shape;
                        for (HSLFTextParagraph hslfTextParagraph : hslfTextShape) {
                            for (HSLFTextRun hslfTextRun : hslfTextParagraph) {
                                hslfTextRun.setFontFamily("宋体");
                            }
                        }
                    }
                }
 
                FileOutputStream out = null;
                try {
                    slide.draw(graphics);
                    File pngFile = new File(outImgPath+"/"+idx+".png");
                    out = new FileOutputStream(pngFile);
                    ImageIO.write(img, "png", out);
                    pngFileList.add(pngFile);
                } catch (Exception e) {
                } finally {
                    try {
                        if (out != null) {
                            out.flush();
                            out.close();
                        }
 
                        if (graphics != null) {
                            graphics.dispose();
                        }
 
                        if (img != null) {
                            img.flush();
                        }
                    } catch (IOException e) {
                    }
                }
                idx++;
            }
        } catch (Exception e) {
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
 
                if (ppt != null) {
                    ppt.close();
                }
            } catch (Exception e) {
            }
        }
    }

}
